package com.ruoyi.ahs.util;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ruoyi.ahs.cache.AhsCache;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.system.domain.RushConfig;
import com.ruoyi.system.domain.RushTask;
import com.ruoyi.system.domain.ahs.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.SneakyThrows;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * 抢购任务对象 rush_task
 *
 * @author ruoyi
 * @date 2024-12-22
 */
@Slf4j
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class RushTaskDto extends BaseEntity {
    private static final long serialVersionUID = 1L;
    private Long id;
    private Long gaeaCategoryId;
    private String gaeaCategoryName;
    private Long gaeaBrandId;
    private String gaeaBrandName;
    private Long gaeaProductId;
    private String gaeaProductName;
    private List<Long> gaeaFinenessIds;
    private List<String> gaeaFinenessNames;
    private Map<String, List<Long>> gaeaPricePpvIds;
    private Map<String, List<String>> gaeaPricePpvNames;
    private Map<String, List<Long>> gaeaSkuPpvIds;
    private Map<String, List<String>> gaeaSkuPpvNames;
    private Long minPrice;
    private Long maxPrice;
    private String sortValue;
    private Long pageIndex;
    private Long pageSize;
    private String status;
    private Long frequency;

    private boolean isRunning = false;
    private Thread taskThread;

    @JsonIgnore
    private ProductSearch productSearch;

    public RushTaskDto() {

    }

    public RushTaskDto(RushTask rushTask) {
        if (rushTask == null) {
            return;
        }
        this.setId(rushTask.getId());
        this.setGaeaCategoryId(rushTask.getGaeaCategoryId());
        this.setGaeaCategoryName(rushTask.getGaeaCategoryName());
        this.setGaeaBrandId(rushTask.getGaeaBrandId());
        this.setGaeaBrandName(rushTask.getGaeaBrandName());
        this.setGaeaProductId(rushTask.getGaeaProductId());
        this.setGaeaProductName(rushTask.getGaeaProductName());
        this.setMinPrice(rushTask.getMinPrice());
        this.setMaxPrice(rushTask.getMaxPrice());
        this.setSortValue(rushTask.getSortValue());
        this.setPageIndex(rushTask.getPageIndex());
        this.setPageSize(rushTask.getPageSize());
        this.setStatus(rushTask.getStatus());
        this.setFrequency(rushTask.getFrequency());
        this.setGaeaFinenessIds(JSONUtils.fromJsonToListLong(rushTask.getGaeaFinenessIds()));
        this.setGaeaFinenessNames(JSONUtils.fromJsonToListString(rushTask.getGaeaFinenessNames()));
        this.setGaeaPricePpvIds(JSONUtils.fromJsonToMapStringListLong(rushTask.getGaeaPricePpvIds()));
        this.setGaeaPricePpvNames(JSONUtils.fromJsonToMapStringListString(rushTask.getGaeaPricePpvNames()));
        this.setGaeaSkuPpvIds(JSONUtils.fromJsonToMapStringListLong(rushTask.getGaeaSkuPpvIds()));
        this.setGaeaSkuPpvNames(JSONUtils.fromJsonToMapStringListString(rushTask.getGaeaSkuPpvNames()));
        this.isRunning = false;
    }

    @SneakyThrows
    public ProductSearch getProductSearch() {
        if (productSearch == null) {
            productSearch = new ProductSearch();
            productSearch.setGaeaCategoryId(this.gaeaCategoryId);
            productSearch.setGaeaBrandId(this.gaeaBrandId);
            productSearch.setGaeaProductId(this.gaeaProductId);
            productSearch.setGaeaFinenessIds(this.gaeaFinenessIds);
            productSearch.setGaeaPricePpvIds(this.gaeaPricePpvIds);
            productSearch.setGaeaSkuPpvIds(this.gaeaSkuPpvIds);
            productSearch.setMinPrice(this.minPrice);
            productSearch.setMaxPrice(this.maxPrice);
            productSearch.setSortValue(this.sortValue);
            productSearch.setCityId(AhsCache.getCurrentConfig().getCityId());
        }
        return productSearch;
    }

    public RushTask toRushTask() {
        RushTask rt = new RushTask();
        rt.setId(this.getId());
        rt.setGaeaCategoryId(this.getGaeaCategoryId());
        rt.setGaeaCategoryName(this.getGaeaCategoryName());
        rt.setGaeaBrandId(this.getGaeaBrandId());
        rt.setGaeaBrandName(this.getGaeaBrandName());
        rt.setGaeaProductId(this.getGaeaProductId());
        rt.setGaeaProductName(this.getGaeaProductName());
        rt.setMinPrice(this.getMinPrice());
        rt.setMaxPrice(this.getMaxPrice());
        rt.setSortValue(this.getSortValue());
        rt.setPageIndex(this.getPageIndex());
        rt.setPageSize(this.getPageSize());
        rt.setStatus(this.getStatus());
        rt.setFrequency(this.getFrequency());
        rt.setGaeaFinenessIds(JSONUtils.toJsonString(this.getGaeaFinenessIds()));
        rt.setGaeaFinenessNames(JSONUtils.toJsonString(this.getGaeaFinenessNames()));
        rt.setGaeaPricePpvIds(JSONUtils.toJsonString(this.getGaeaPricePpvIds()));
        rt.setGaeaPricePpvNames(JSONUtils.toJsonString(this.getGaeaPricePpvNames()));
        rt.setGaeaSkuPpvIds(JSONUtils.toJsonString(this.getGaeaSkuPpvIds()));
        rt.setGaeaSkuPpvNames(JSONUtils.toJsonString(this.getGaeaSkuPpvNames()));
        return rt;
    }

    public void start() {
        this.isRunning = true;
        log.info("创建抢购任务{}", this.id);
        RushTaskDto that = this;
        this.taskThread = new Thread(() -> {
            while (isRunning) {
                // 模拟任务执行
                monitorTask(that);
                if (this.frequency != null && this.frequency > 0L) {
                    try {
                        Thread.sleep(this.frequency); // 模拟任务执行时间
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        log.warn("Task {} was interrupted.", this.id);
                    }
                }
            }
        });
        this.taskThread.start();
    }

    public void stop() {
        this.isRunning = false;
        log.info("停止抢购任务{}", this.id);
        if (this.taskThread != null) {
            this.taskThread.interrupt();
        }
    }

    /**
     * 商品下单
     */
    private OrderResult createOrder(Product product) {
        List<Discount> discountList = product.getDiscountList();
        String discountCode = null;
        if (!CollectionUtils.isEmpty(discountList)) {
            discountCode = discountList.stream()
                    .filter(d -> "1001".equals(d.getDiscountType()))
                    .map(Discount::getCode)
                    .findFirst()
                    .orElse(discountList.get(0).getCode());
        }
        Sensors sensors = AhsCache.getSensors();
        RushConfig config = AhsCache.getCurrentConfig();
        Order orderDTO = new Order();
        orderDTO.setProductSerialNo(product.getProductNo());
        orderDTO.setCityId(config.getCityId());
        orderDTO.setActivityCode(discountCode != null ? discountCode : config.getActivityCode());
        orderDTO.setPickupType(config.getPickupType());
        orderDTO.setAddressId(config.getAddressId() != null ? config.getAddressId() : AhsCache.getAddressId());
        orderDTO.setSensors(sensors);
        return AhsUtils.createOrder(orderDTO);
    }

    private void monitorTask(RushTaskDto task) {
        try {
            ProductSearch productSearch = task.getProductSearch();
            SearchResult searchResult = AhsUtils.search(productSearch);
            if (searchResult.isSuccess()) {
                List<Product> productList = searchResult.getData();
                if (CollectionUtils.isEmpty(productList)) {
                    return;
                }
                for (Product product : productList) {
                    if (product != null) {
                        log.info("抢购消费者 {} 正在下单产品: {}", Thread.currentThread().getName(), product);
                        OrderResult orderResult = createOrder(product);
                        if (orderResult.isSuccess()) {
                            WeChatBotMessageSender.sendMessage(String.format("抢购商品成功！订单号:%s", orderResult.getData()), null);
                        } else {
                            WeChatBotMessageSender.sendMessage(String.format("抢购失败！原因:%s", orderResult.getResultMessage()), 1);
                        }
                    }
                }
            } else {
                WeChatBotMessageSender.sendMessage("抢购失败" + JSONObject.toJSONString(searchResult));
                throw new BaseException("抢购失败", JSONObject.toJSONString(searchResult));
            }
        } catch (Exception e) {
            //WeChatBotMessageSender.sendMessage("抢购异常，异常信息：" );
            log.error("抢购异常，异常信息：", e);
        }
    }
}
